package controller

import (
	. "gddgame.cc/galaxy/common/dsl/web"
	"gddgame.cc/galaxy/core/models"
	"gddgame.cc/galaxy/utils"
	"gddgame.cc/galaxy/utils/def"
)

func GetLeaderboard(context def.Context, app *models.App, identity string) (*models.AppLeaderboard, error) {
	var leaderboard models.AppLeaderboard
	var err error
	err = wrap.Cache("app/"+utils.ToString(app.Id)+"/leaderboard/"+identity, &leaderboard, func() error {
		if ok, err := models.AppLeaderboardModel.Query().Where("=", "app_id", app.Id).Where("=", "identity", identity).One(&leaderboard); !ok {
			return EmptyExceptionDetail("leaderboard不存在", err)
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return &leaderboard, nil
}

func UpdateLeaderboard(context def.Context, app *models.App, userOpen *models.UserOpen, leaderboard *models.AppLeaderboard, value int) (int, error) {
	var leaderboardUser models.AppLeaderboardUser
	var err error
	if ok, _ := models.AppLeaderboardUserModel.Query().
		Where("=", "app_id", app.Id).
		Where("=", "user_id", userOpen.UserId).
		Where("=", "leaderboard_id", leaderboard.Id).One(&leaderboardUser); ok {
		// 修改
		if !leaderboard.Current {
			if leaderboard.Asc {
				if leaderboardUser.Value < value {
					return leaderboardUser.Value, nil
				}
			} else {
				if leaderboardUser.Value > value {
					return leaderboardUser.Value, nil
				}
			}
		}

		if _, err = models.AppLeaderboardUserModel.PK(leaderboardUser.Id).Update(map[string]interface{}{
			"value": value,
		}); err != nil {
			return 0, SystemExceptionDetail("更新排行榜失败", err)
		}
		return value, nil
	}
	if _, err := models.AppLeaderboardUserModel.Insert(&models.AppLeaderboardUser{
		UserId:        userOpen.UserId,
		AppId:         app.Id,
		LeaderboardId: leaderboard.Id,
		Value:         value,
	}); err != nil {
		return 0, SystemExceptionDetail("更新排行榜失败", err)
	}
	return value, nil
}

func GetLeaderboardNumber(context def.Context, app *models.App, userOpen *models.UserOpen, leaderboard *models.AppLeaderboard) (int, error) {
	var leaderboardUser models.AppLeaderboardUser
	if ok, _ := models.AppLeaderboardUserModel.Query().
		Where("=", "app_id", app.Id).
		Where("=", "user_id", userOpen.UserId).
		Where("=", "leaderboard_id", leaderboard.Id).One(&leaderboardUser); ok {
		return leaderboardUser.Value, nil
	}
	return 0, nil
}
